﻿using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using ConfOrder.Properties;
using ConfOrderDS;
using ConfOrderDS.AppDSTableAdapters;
using DevExpress.Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace ConfOrder
{
    public partial class OrderReport : XForm
    {
        public OrderReport()
        {
            InitializeComponent();
        }

        BindingSource bsFabrics, bsDagilim;

        private void Orders_Load(object sender, EventArgs e)
        {
            MainToolbar.Visible = true;
            TAM.COOrderTableAdapter = new COOrderTableAdapter();
            TAM.COBreakdownTableAdapter = new COBreakdownTableAdapter();

            GetDetails("COOrder;COBreakdown", "COGetOrders2", 0, AppSession.UserInfo.CustomerId, bciShowAll.Checked);

            ds.COOrder.Columns.Add("Total", typeof(int), "SUM(Child(FK_COBreakdown_COOrder_OrderId).TotalComputed)");
            ds.COBreakdown.Columns.Add("Total", typeof(int), "IsNull(A01, 0) + IsNull(A02, 0) + IsNull(A03, 0) + IsNull(A04, 0) + IsNull(A05, 0) + IsNull(A06, 0) + IsNull(A07, 0) + IsNull(A08, 0) + IsNull(A09, 0) + IsNull(A10, 0) + IsNull(A11, 0) + IsNull(A12, 0) + IsNull(A13, 0) + IsNull(A14, 0) + IsNull(A15, 0) + IsNull(A16, 0) + IsNull(A17, 0) + IsNull(A18, 0) + IsNull(A19, 0) + IsNull(A20, 0) + IsNull(A21, 0) + IsNull(A22, 0) + IsNull(A23, 0) + IsNull(A24, 0) + IsNull(A25, 0) + IsNull(A26, 0) + IsNull(A27, 0) + IsNull(A28, 0)");


            bsFabrics = new BindingSource(ds, "COOrder");
            bsDagilim = new BindingSource(bsFabrics, "FK_COBreakdown_COOrder_OrderId");

            InitGridView(gvOrders, bsFabrics);
            InitGridView(gvDagilim, bsDagilim);

            gvOrders.Columns["Season"].OptionsColumn.AllowEdit = false;
            gvOrders.Columns["Season"].VisibleIndex = 3;

            gvOrders.MakeReadOnly();
            gvDagilim.MakeReadOnly();

            gvDagilim.MakeColumnInvisible("COBreakdownId", "TotalComputed", "COOrderId");
            gvOrders.MakeColumnInvisible("CustomerId", "Product5Id", "Product6Id", "Part", "ProductId", "Product1Id", "Product2Id", "Product3Id", "Product4Id", "COOrderId");

            gvOrders.YanYanaGetirCoklu("COStyleId", "Total", "ETD", "State", "OrderedDate", "UserSubmitted");

            gvOrders.Columns["COStyleId"].ColumnEdit = RepositoryManager.riStyle;
            //GridManager gm = new GridManager(gvOrders);
            GridManager gm = GridManager.GetManager(gvOrders);
            ordersMenu = gm.GridMenu;

            gvOrders.Columns["State"].ColumnEdit = RepositoryManager.riState;
            gvOrders.Columns["OrderRefId"].ColumnEdit = RepositoryManager.riOrderRef;

            RepositoryItemGridLookUpEdit ri = RepositoryManager.riDagilim;
            gvOrders.Columns["DagilimId"].ColumnEdit = ri;
            ri.Closed += ri_Closed;
            bsFabrics.CurrentChanged += bsFabrics_CurrentChanged;

            gvOrders.SetCaptions("TalepTipiId:Order Type", "DagilimId:Breakdown Type", "COStyleId:Style");

            DagilimId = bsFabrics.GetCurrentValue("DagilimId").ToIntNN();
            DagilimChanged();

            gvOrders.BestFitColumns();
            gvDagilim.BestFitColumns();
            //gvOrders.Columns["COOrderId"].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            gvOrders.Columns["Pos"].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;

            gvOrders.AddSummary("Total");
            gvDagilim.AddSummary("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10",
                            "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20",
                            "A21", "A22", "A23", "A24", "A25", "A26", "A27", "A28");

            scc.SizeChanged += new EventHandler(MySizeChanged);
            gvOrders.SelectionChanged += gvOrders_SelectionChanged;

            gvOrders.SetViewCaption("Orders");
            gvDagilim.SetViewCaption("Order Breakdown");

            gvOrders.CustomRowFilter += gvOrders_CustomRowFilter;
        }




        int DagilimId = 0;
        void bsFabrics_CurrentChanged(object sender, EventArgs e)
        {
            DagilimId = bsFabrics.GetCurrentValue("DagilimId").ToIntNN();
            DagilimChanged();
        }

        void ri_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            DagilimId = (sender as BaseEdit).EditValue.ToIntNN();
            DagilimChanged();
        }

        private void DagilimChanged()
        {
            try
            {
                gvDagilim.CloseEditor();
                gvDagilim.BeginUpdate();

                AppDS.DagilimRow r = RepositoryManager.dsi.Dagilim.FindByDagilimId(DagilimId);
                if (r != null)
                    for (int i = 1; i <= 28; i++)
                    {
                        string fieldName = String.Format("A{0:00}", i);
                        string cap = r[String.Format("A{0:00}", i)].ToString();

                        gvDagilim.Columns[fieldName].VisibleIndex = 100 + i;

                        if (cap != "")
                            gvDagilim.Columns[fieldName].Caption = cap;
                        else
                            gvDagilim.Columns[fieldName].Visible = false;
                        //gvDagilim.Columns[fieldName].Caption = cap != string.Empty ? cap : " ";
                    }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                gvDagilim.EndUpdate();
                gvDagilim.BestFitColumns();
            }
        }

        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Save();
            gvDagilim.BestFitColumns();
        }

        private void bbiRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ds.COOrder.Clear();
            ds.COBreakdown.Clear();
            GetDetails("COOrder;COBreakdown", "COGetOrders2", 0, AppSession.UserInfo.CustomerId, bciShowAll.Checked);

        }

        void gvOrders_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (gvOrders.SelectedRowsCount == 0)
                newMenuCaption = "";
            else if (gvOrders.SelectedRowsCount == 1)
                newMenuCaption = "Copy this order";
            else
                newMenuCaption = "Copy " + gvOrders.SelectedRowsCount + " selected orders";

            ordersMenu.RemoveMenu(lastMenuCaption);
            if (newMenuCaption != "")
            {
                ordersMenu.AddMenu(newMenuCaption, CopyOrders, Resources.Ok24);
                lastMenuCaption = newMenuCaption;
            }
        }

        GridMenu ordersMenu;
        string lastMenuCaption = "";
        string newMenuCaption = "";

        void CopyOrders(object sender, EventArgs e)
        {
            DialogResult dr = XtraMessageBox.Show("Selected orders will be copied as new orders.\r\n\r\nAre you sure?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
                string OrderIds = "";
                List<int> orderIds = new List<int>();
                foreach (int rowHandle in gvOrders.GetSelectedRows())
                {
                    if (rowHandle > -1)
                    {
                        OrderIds += gvOrders.GetRowCellValue(rowHandle, "COOrderId").ToString() + ",";
                        //int orderId = (int)gvOrders.GetRowCellValue(rowHandle, "COOrderId");
                        //orderIds.Add(orderId);                        
                    }
                }

                OrderIds = OrderIds.RemoveIfEndsWith(",");
                ExecQuery("[COCopyOrder]", OrderIds);
                Notify("Copied successfully.");
            }
        }

        bool reporting = false;
        private void btnExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvOrders.CloseEditor();
            gvOrders.UpdateCurrentRow();

            //System.Data.DataTable dt = ds.COOrder.Copy();
            //dt = dt.Select("isnull(State,'') <> 'Sent'", "").CopyToDataTable();

            reporting = true;
            gvOrders.RefreshData();
            using (SaveFileDialog saver = new SaveFileDialog())
            {
                saver.Filter = "Excel Files (*.xlsx)|xlsx";
                DialogResult dr = saver.ShowDialog();
                string fileName = saver.FileName;
                if (!fileName.ToLower().EndsWith(".xlsx"))
                    fileName += ".xlsx";

                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    gvOrders.ExportToXlsx(fileName);
                    Process.Start(fileName);
                }
            }
            reporting = false;
            gvOrders.RefreshData();
        }

        void gvOrders_CustomRowFilter(object sender, DevExpress.XtraGrid.Views.Base.RowFilterEventArgs e)
        {
            if (reporting)
            {
                if (gvOrders.GetRowCellValue(e.ListSourceRow, "State").ToStringNN() == "S")
                    e.Visible = false;
                else
                    e.Visible = true;

                e.Handled = true;
            }
        }
    }
}